<?php

class photos extends Module {
	
	private
		$aPhotosInAlbum = array (),
		$aUserAlbums    = null;
	
	public function __construct () {
		parent::__construct (__CLASS__);
		$this->extend ('__photos_ajax');
		$this->extend ('__photos_mail');
		$this->extend ('__custom_photos');
	}
	
	/**
	 * @return ModuleResponse
	 */
	public function __default () {
		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}
		
		return $this->getObjectsList (
			TypesController::getInstance()->getTypeByName ('photo'),
			'photos/photosList',
			'date',
			false,
			null,
			array (
				'page' => $currentPage,
				'onpage' => (int) Regedit::getInstance()->get ('//modules/photos/photos_on_page')
			)
		);
	}
	
	/**
	 * Фотоальбомы пользователя
	 * @return ModuleResponse
	 */
	public function user () {
		$typesController = TypesController::getInstance ();
		
		$oTypeUser = $typesController->getTypeByName ('user');
		$oTypePhotoalbum = $typesController->getTypeByName ('photoalbum');
		
		$requestUserLogin = getRequest ('param0');
		
		$selUser = new Selection;
		$selUser->addType ($oTypeUser);
		$selUser->addFilter ('login', $requestUserLogin);
		$selUser->addLimit (1);
		
		$res = $selUser->getList ();
		
		if (count ($res) == 0) {
			throw new NotFound;
		}
		
		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}
		
		$aFiltes = array ('owner_id' => $res[0][0]);
		
		return $this->getObjectsList (
			$oTypePhotoalbum,
			'photos/albumsList',
			'update',
			false,
			$aFiltes,
			array (
				'page' => $currentPage,
				'onpage' => (int) Regedit::getInstance()->get ('//modules/photos/albums_on_page')
			),
			array (
				'user-login' => $requestUserLogin,
				'user-id' => $res[0][0]
			)
		);	
	}
	
	/**
	 * Поиск по тегам
	 * @return ModuleResponse
	 */
	public function tag () {
		if (getRequest ('param0') == 'go' && getRequest ('tag')) {
			redirect (HTTP_HOST . '/photos/tag/' . getRequest ('tag'));
		}
		
		$requestTag = getRequest ('param0');

		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}
		
		return $this->getObjectsList (
			TypesController::getInstance()->getTypeByName ('photo'),	
			'photos/photosList',
			'date',
			false,
			array (
				'tags' => $requestTag
			),
			array (
				'page' => $currentPage,
				'onpage' => (int) Regedit::getInstance()->get ('//modules/photos/photos_on_page')
			),
			array ('tag-filter' => $requestTag) 
		);
	}
	
	/**
	 * Список фотографий в заданном фотоальбоме
	 * @return ModuleResponse
	 */
	public function album () {
		$oTypeAlbum = TypesController::getInstance()->getTypeByName ('photoalbum');
		
		$requestAlbumId = getRequest ('param0', 'int');
		
		if (!$oAlbum = ObjectsController::getInstance()->getObject ($oTypeAlbum, $requestAlbumId)) {
			throw new NotFound;
		}
		
		$this->setPageTitle ($oAlbum->getValue ('title') . lang('header_album',__CLASS__));
		
		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}
		
		$aFilters = array ('album_id' => $requestAlbumId);
		
		return $this->getObjectsList (
			TypesController::getInstance()->getTypeByName ('photo'),	
			'photos/photosList',
			'date',
			true,
			$aFilters,
			array (
				'page' => $currentPage,
				'onpage' => (int) Regedit::getInstance()->get ('//modules/photos/photos_on_page')
			),
			array (
				'album-id' => $requestAlbumId,
				'album-owner-id' => $oAlbum->getValue ('owner_id')
			) 
		);
	}
	
	/**
	 * Просмотр фотографии
	 * @return ModuleResponse
	 */
	public function photo () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oTypeAlbum = $typesController->getTypeByName ('photoalbum');
		$oTypePhoto = $typesController->getTypeByName ('photo');
		
		$requestPhotoId = getRequest ('param0', 'int');
		
		if (!$oPhoto = $objectsController->getObject ($oTypePhoto, $requestPhotoId)) {
			throw new NotFound;
		}
		
		$oAlbum = $objectsController->getObject ($oTypeAlbum, $oPhoto->getValue ('album_id'));
		
		$this->setPageTitle ($oPhoto->getValue ('title') . lang('header_photo',__CLASS__));
		
		// Получаем все фотографии в альбоме
		$sel = new Selection;
		$sel->addType ($oTypePhoto);
		$sel->addFilter ('album_id', $oAlbum->getId ());
		$sel->addSelectedProperty ('photo');
		
		$res = $sel->getList ();
		
		$currentPhotoPost = 1;
		$back = 0;
		$for = $res[0][0];
		$pos = 0;
		$total = count ($res);
		
		// Складываем массив всех фотографий из альбома
		foreach ($res as $row) {
			$this->aPhotosInAlbum[$pos] = array (
				'id' => $row[0],
				'photo' => $row['photo']
			);
			
			if ($row[0] == $requestPhotoId) {
				$currentPhotoPost = $pos+1;
				
				if ($pos > 0) {
					$back = $this->aPhotosInAlbum[$pos-1]['id'];
				}
				if ($pos+1 < $total) {
					$for = $res[$pos+1][0];
				}
			}
			
			$pos++;
		}
		
		$oPhoto->setAttribute ('current-position', $currentPhotoPost);
		$oPhoto->setAttribute ('previous-id', $back);
		$oPhoto->setAttribute ('next-id', $for);
		if (userGroup (ExplaySession::getUser()->getValue ('group')) != 'guest' && $oPhoto->getValue ('owner_id') != ExplaySession::getUserId ()) {
			$oPhoto->setAttribute ('allow-vote', '1');
		} else {
			$oPhoto->setAttribute ('allow-vote', '0');
		}
		
		$response = new ModuleResponse;
		$response->setTemplate ('photos/viewPhoto');
		$response->setAttribute ('album-id', $oPhoto->getValue ('album_id'));
		$response->setAttribute ('album-owner-id', $oAlbum->getValue ('owner_id'));
		$response->addObject ($oPhoto);
		
		return $response;
	}
	
	/**
	 * Создание нового фотоальбома
	 * @return ModuleResponse
	 */
	public function create_album () {
		$oTypeAlbum = TypesController::getInstance()->getTypeByName ('photoalbum');
		
		$form = new Form ($oTypeAlbum, 'new');
		$form->buildFromType ();
		
		if (getRequest ('param0') == 'save') {
			$aProperties = $this->getRequestData('new', $oTypeAlbum);
			
			$object = new Object ($oTypeAlbum);
			$object->setValues ($aProperties);
			$object->setValue ('date', time ());
			$object->setValue ('update', $object->getValue ('date'));
			$object->setValue ('owner_id', ExplaySession::getUserId ());
			$object->setValue ('count_photos', 0);
			
			$aErrors = $this->getValidateErrors ($object);
			
			if (count ($aErrors)) {
				$form->setErrors ($aErrors);
				$form->setValues ($aProperties);
			} else {
				$object->createNew ();
				
				redirect (HTTP_HOST . '/photos/album/' . $object->getId ());
			}
		}
		
		$this->setPageTitle (lang('header_create_album',__CLASS__));
		
		$response = new ModuleResponse;
		$response->setTemplate ('photos/formAlbum');
		$response->addObject ($form);
		
		return $response;
	}
	
	/**
	 * Редактирование фотоальбома
	 * @return ModuleResponse
	 */
	public function edit_album () {
		$oTypeAlbum = TypesController::getInstance()->getTypeByName ('photoalbum');
		
		$requestId = getRequest ('param0', 'int');
		
		if (!$oAlbum = ObjectsController::getInstance()->getObject ($oTypeAlbum, $requestId)) {
			throw new NotFound;
		}
		
		if ($oAlbum->getValue ('owner_id') != ExplaySession::getUserId ()) {
			throw new AccessException (lang('error_edit_album_not_owner',__CLASS__));
		}
		
		$form = new Form ($oTypeAlbum, $requestId);
		$form->buildFromType ();
		
		if (getRequest ('param1') == 'save') {
			$aProperties = $this->getRequestData($requestId, $oTypeAlbum);
			
			$oAlbum->setValues ($aProperties);
						
			$aErrors = $this->getValidateErrors ($oAlbum);
			
			if (count ($aErrors)) {
				$form->setErrors ($aErrors);
			} else {
				$oAlbum->save ();
				
				redirect (HTTP_HOST . '/photos/edit_album/' . $requestId . '?ok');
			}
		}
		
		$form->setValues ($oAlbum->getValues ());
		
		$this->setPageTitle (lang('header_edit_album',__CLASS__));
		
		$response = new ModuleResponse;
		$response->setTemplate ('photos/formAlbum');
		
		if (getRequest ('ok', 'bool')) {
			$response->addObject (new SystemMessage (lang('message_album_edited',__CLASS__)));
		}
		
		$response->addObject ($form);
		
		return $response;
	}
	
	/**
	 * Загрузка фотографий
	 * @return ModuleResponse
	 */
	public function upload () {
		$typesController = TypesController::getInstance ();
		$oTypePhoto = $typesController->getTypeByName ('photo');
		$oTypeAlbum = $typesController->getTypeByName ('photoalbum');
		$objectsController = ObjectsController::getInstance ();
		
		$this->setPageTitle (lang('header_upload',__CLASS__));
		
		$albumId = getRequest ('param0', 'int');
		$maxUpload = (int) Regedit::getInstance()->get ('//modules/photos/max_upload');
		
		$response = new ModuleResponse;
		$response->setTemplate ('photos/upload');
		$response->setAttribute ('album-id', $albumId);
		$response->setAttribute ('max-upload', $maxUpload);
		
		if ($albumId == 0) {
			return $response;
		}
		
		if (!$oAlbum = $objectsController->getObject ($oTypeAlbum, $albumId)) {
			$response->setAttribute ('album-id', '0');
			$response->addObject (new SystemError (lang('error_upload_photos_none_album',__CLASS__)));
			return $response;
		}
		
		if ($oAlbum->getValue ('owner_id') != ExplaySession::getUserId ()) {
			$response->setAttribute ('album-id', '0');
			$response->addObject (new SystemError (lang('error_upload_photos_wrong_album',__CLASS__)));
			return $response;
		}
		
		if (getRequest ('param1') == 'go') {			
			if (!$oField = $oTypePhoto->getFieldByName ('photo')) {
				throw new CoreException ('Look me');
			}
			
			$aPhotos = array ();
			
			for ($i = 1; $i <= $maxUpload; ++$i) {
				if (isset ($_FILES['photo']['tmp_name'][$i]) && mb_strlen ($_FILES['photo']['tmp_name'][$i])) {
					$src = FilesController::uploadImage (
						array (
							'name'     => $_FILES['photo']['name'][$i],
							'tmp_name' => $_FILES['photo']['tmp_name'][$i],
							'error'    => $_FILES['photo']['error'][$i],
							'size'     => $_FILES['photo']['size'][$i],
							'type'     => $_FILES['photo']['type'][$i]
						),
						$oField
					);
					
					if ($src == '') {
						$response->addObject (new SystemError (lang('error_upload',__CLASS__)));
						return $response;
					}
					
					$object = new Object ($oTypePhoto);
					$object->setValues (array (
						'owner_id' => ExplaySession::getUserId (),
						'photo' => $src,
						'date' => time (),
						'count_comments' => '0',
						'album_id' => $albumId,
						'title' => lang('without_name', __CLASS__)
					));
					
					$aErrors = $this->getValidateErrors ($object);
					
					if (count ($aErrors)) {
						$response->addObject (new SystemError (lang('error_upload',__CLASS__)));
						return $response;
					}
					
					$aPhotos[] = $object;
				}
			}
			
			if (!count ($aPhotos)) {
				$response->addObject (new SystemError (lang('error_upload_empty_request',__CLASS__)));
				return $response;
			}
			
			$url = '/photos/edit/' . $albumId . '?';
			$n = 0;
			
			foreach ($aPhotos as $oPhoto) {
				$oPhoto->createNew ();
				$url .= 'photo[]=' . $oPhoto->getId () . '&';
				$n++;
			}
			
			$this->logPhotos ($aPhotos, $albumId);
			
			$cntPhotos = $oAlbum->getValue ('count_photos') + $n;
			$oAlbum->setValue ('count_photos', $cntPhotos);
			$oAlbum->setValue ('update', time ());
			$oAlbum->save ();
			
			redirect (HTTP_HOST . $url);
		}
		
		return $response;
	}
	
	/**
	 * Редактирование фотографий
	 * @return ModuleResponse
	 */
	public function edit () {
		$typesController = TypesController::getInstance ();
		$oTypePhoto = $typesController->getTypeByName ('photo');
		$oTypeAlbum = $typesController->getTypeByName ('photoalbum');
		$objectsController = ObjectsController::getInstance ();
		
		$albumId = getRequest ('param0', 'int');
		
		if (!$oAlbum = $objectsController->getObject ($oTypeAlbum, $albumId)) {
			throw new NotFound;
		}
		
		$userGroup = userGroup (ExplaySession::getUser()->getValue ('group'));
		
		if ($oAlbum->getValue ('owner_id') != ExplaySession::getUserId() && $userGroup != 'admin' && $userGroup != 'moderator') {
			throw new NotFound;
		}
		
		if (empty ($_REQUEST['photo']) || !is_array ($_REQUEST['photo'])) {
			throw new ControllerException (lang('error_edit_photos_wrong_request',__CLASS__));
		}
		
		$aObjectsIds = $_REQUEST['photo'];
		
		$aPhotos = array ();
		
		foreach ($aObjectsIds as $photoId) {
			if (!$object = $objectsController->getObject ($oTypePhoto, $photoId)) {
				throw new NotFound;
			}
			if ($object->getValue ('album_id') != $albumId) {
				continue;
			}
			$aPhotos[] = $object;
		}
		
		if (count ($aPhotos) == 0) {
			throw new ControllerException (lang('error_edit_photos_objects_null',__CLASS__));
		}
		
		$this->setPageTitle (lang('header_edit_photos',__CLASS__));
		
		$response = new ModuleResponse;
		$response->setTemplate ('photos/formPhoto');
		$response->setAttribute ('album-id', $albumId);
		
		$isSaving = getRequest ('param1') == 'save' ? true : false;
		$isCool = true;
		
		foreach ($aPhotos as $oPhoto) {
			$form = new Form ($oTypePhoto, $oPhoto->getId ());
			$form->buildFromType ();
			
			if ($isSaving) {
				$lastAlbumId = $oPhoto->getValue ('album_id');
				
				$oPhoto->setValues ($this->getRequestData ($oPhoto->getId (), $oTypePhoto));
				
				if ($oPhoto->getValue ('title') == '') {
					$oPhoto->setValue ('title', lang('without_name', __CLASS__));
				}
				
				$aErrors = $this->getValidateErrors ($oPhoto);
				
				if (empty ($aErrors['album_id'])) {
					$testSel = new Selection;
					$testSel->addType ($oTypeAlbum);
					$testSel->addFilter ('id', $oPhoto->getValue ('album_id'));
					$testSel->addFilter ('owner_id', ExplaySession::getUserId ());
					
					if ($testSel->getTotalCount () == 0) {
						$aErrors['album_id'] = lang ('error_edit_photos_none_such_album',__CLASS__);
					}
				}
				
				if (count ($aErrors)) {
					$form->setErrors ($aErrors);
					$isCool = false;
				} else {
					$oPhoto->save ();
					
					if ($oPhoto->getValue ('album_id') != $lastAlbumId) {
						$oAlbum = $objectsController->getObject ($oTypeAlbum, $lastAlbumId);
						$cntPhotos = $oAlbum->getValue ('count_photos') - 1;
						$oAlbum->setValue ('count_photos', $cntPhotos);
						$oAlbum->save ();
						
						$oAlbum = $objectsController->getObject ($oTypeAlbum, $oPhoto->getValue ('album_id'));
						$cntPhotos = $oAlbum->getValue ('count_photos') + 1;
						$oAlbum->setValue ('count_photos', $cntPhotos);
						$oAlbum->setValue ('update', time ());
						$oAlbum->save ();
					}
				}
			}
			
			$form->setValues ($oPhoto->getValues ());
			
			$response->addObject ($form);
		}
		
		if ($isSaving && $isCool) {
			redirect (HTTP_HOST . '/photos/album/' . $albumId);
		}
		
		return $response;
	}
	
	/**
	 * Удаление фотографии
	 * @return void
	 */
	public function delete_photo () {
		$typesController = TypesController::getInstance ();
		$oTypePhoto = $typesController->getTypeByName ('photo');
		$oTypeAlbum = $typesController->getTypeByName ('photoalbum');
		$objectsController = ObjectsController::getInstance ();
		
		$photoId = getRequest ('param0', 'int');
		
		if (!$oPhoto = $objectsController->getObject ($oTypePhoto, $photoId)) {
			throw new NotFound;
		}
		
		$userGroup = userGroup (ExplaySession::getUser()->getValue ('group'));
		
		if ($oPhoto->getValue ('owner_id') != ExplaySession::getUserId() && $userGroup != 'admin' && $userGroup != 'moderator') {
			throw new NotFound;
		}
		
		$albumId = $oPhoto->getValue ('album_id');
		
		$oAlbum = $objectsController->getObject ($oTypeAlbum, $albumId);
		$cntPhotos = $oAlbum->getValue ('count_photos') - 1;
		$oAlbum->setValue ('count_photos', $cntPhotos);
		
		if ($oAlbum->getValue ('preview') == $oPhoto->getValue ('photo')) {
			$oAlbum->setValue ('preview', '');
		}
		
		$oAlbum->save ();
		
		$oPhoto->delete ();
		
		redirect (HTTP_HOST . '/photos/album/' . $albumId);
	}
	
	/**
	 * Удаление фотоальбома
	 * @return void
	 */
	public function delete_album () {
		$typesController = TypesController::getInstance ();
		$oTypePhoto = $typesController->getTypeByName ('photo');
		$oTypeAlbum = $typesController->getTypeByName ('photoalbum');
		$objectsController = ObjectsController::getInstance ();
		
		$albumId = getRequest ('param0', 'int');
		
		if (!$oAlbum = $objectsController->getObject ($oTypeAlbum, $albumId)) {
			throw new NotFound;
		}
		
		$userGroup = userGroup (ExplaySession::getUser()->getValue ('group'));
		
		if ($oAlbum->getValue ('owner_id') != ExplaySession::getUserId() && $userGroup != 'admin' && $userGroup != 'moderator') {
			throw new NotFound;
		}
		
		// А надо ли это?
				
		$sel = new Selection;
		$sel->addType ($oTypePhoto);
		$sel->addFilter ('album_id', $albumId);
		
		$res = $sel->getList ();
		
		foreach ($res as $row) {
			$objectsController->getObject ($oTypePhoto, $row[0])->delete ();
		}
		
		$oAlbum->delete ();
		
		redirect (HTTP_HOST . '/photos/user/' . ExplaySession::getUser()->getValue ('login'));
	}
	
	/**
	 * Получить последние фотографии
	 * @return ModuleResponse
	 */
	public function getLastPhotos($count) {
		$sel = new Selection;
		$sel->addType(TypesController::getInstance()->getTypeByName('photo'));
		$sel->setOrder('date', false);
		$sel->addLimit($count);
		
		$aObjects = ObjectsController::getInstance()->getObjectsList($sel->getList());
		
		$response = new ModuleResponse;
		
		foreach ($aObjects as $object) {
			$response->addObject($object);
		}
		
		return $response;
	}
	
	/**
	 * Получить список фотоальбомов пользователя (для выбора альбома при загрузке фотографий)
	 * @param integer $slectedId id выбранного фотоальбома
	 * @return ModuleResponse
	 */
	public function getUserAlbumsSelection ($slectedId = 0) {
		if ($this->aUserAlbums === null) {
			$this->aUserAlbums = array ();
			
			$objectsController = ObjectsController::getInstance();
			$oType = TypesController::getInstance()->getTypeByName ('photoalbum');
			
			$sel = new Selection;
			$sel->addType ($oType);
			$sel->addFilter ('owner_id', ExplaySession::getUserId ());
			
			$aObjects = $objectsController->getObjectsList($sel->getList ());
			
			foreach ($aObjects as $object) {
				$this->aUserAlbums[] = $object;
			}
		}
		
		$response = new ModuleResponse;
		
		foreach ($this->aUserAlbums as $object) {
			$object->setAttribute ('selected', $slectedId == $object->getId () ? '1' : '0');
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	/**
	 * Получить фотоальбомы пользователя
	 * @param integer $userId id пользователя
	 * @param integer $albumId id альбома
	 * @return ModuleResponse
	 */
	public function getUserAlbums ($userId, $albumId = false, $limit = 4) {
		$objectsController = ObjectsController::getInstance ();
		
		$oTypeAlbum = TypesController::getInstance()->getTypeByName ('photoalbum');
		
		$sel = new Selection;
		$sel->addType ($oTypeAlbum);
		$sel->addFilter ('owner_id', $userId);
		if ($albumId) {
			$sel->addFilter ('id', $albumId, '!=');
		}
		$sel->setOrder ('update');
		$sel->addLimit ((int) $limit);
		
		$aObjects = $objectsController->getObjectsList($sel->getList ());
		
		$response = new ModuleResponse;
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	/**
	 * Облако фототегов
	 * @return ModuleResponse
	 */
	public function getTagsCloud () {
		$aTags = FDump::getCountObjectValues (array (TypesController::getInstance()->getTypeByName ('photo')), 'tags');
		
		$k = 40 / (log ($aTags['max'] - $aTags['min'] + 1.1));
		
		$res = array ();
		
		for ($i = 0; $i < 50; ++$i) {
			if (!isset ($aTags['values'][$i])) {
				break;
			}
			
			$size = log ($aTags['values'][$i]['cnt'] + 1 - $aTags['min']) * $k;
			$size = $size > 10 ? $size : 10;
			$size = $size < 40 ? $size : 40;
			
			$res[]['tag'] = array (
				'value' => $aTags['values'][$i]['value'],
				'cnt'   => $aTags['values'][$i]['cnt'],
				'size'  => $size
			);
		}
		
		$response = new ModuleResponse;
		$response->addObject (new Array2XML ('tags', $res));
		
		return $response;
	}
	
	/**
	 * Список фотографий в текущем альбоме
	 * @return ModuleResponse
	 */
	public function getAlbumPhotos () {
		
		$arr = array ();
		
		foreach ($this->aPhotosInAlbum as $photo) {
			$arr[]['photo'] = $photo;
		}
		
		$response = new ModuleResponse;
		$response->addObject (new Array2XML ('photos', $arr));
		
		return $response;
	}
	
	/**
	 * Обработка списка фотографий для модуля Лента
	 * @param string $sPhotos
	 * @param integer $max количество выводимых фотографий
	 * @return ModuleResponse
	 */
	public function getLentaPreview ($sPhotos, $max) {
		$aPhotos = explode (',', $sPhotos);
		
		$responseArr = array ();
		
		$n = 1;
		foreach ($aPhotos as $photo) {
			if ($n > $max) {
				break;
			}
			
			$photo = explode ('=', trim ($photo));
			
			$responseArr[]['photo'] = array (
				'path' => $photo[0],
				'id' => $photo[1]
			);
			
			++$n;
		}
		
		$response = new ModuleResponse;
		$response->addObject (new Array2XML ('photos', $responseArr));
		
		return $response;
	}
	
	private function getObjectsList (Type $oType, $sTemplate, $order, $asc, array $aCustomFilters = null, array $aPages = null, array $responseAttributes = null) {
		$objectsController = ObjectsController::getInstance ();
		
		$sel = new Selection;
		$sel->addType ($oType);
		
		if ($aCustomFilters !== null) {
			foreach ($aCustomFilters as $fieldName => $filterValue) {
				$sel->addFilter ($fieldName, $filterValue);
			}
		}
		
		$sel->setOrder ($order, $asc);
		
		if ($aPages === null) {
			$aPages = array (
				'page' => 0,
				'onpage' => 12
			);
		}
		
		$sel->addLimit ($aPages['page']*$aPages['onpage'], $aPages['onpage']);
		
		$aObjects = $objectsController->getObjectsList($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setTemplate ($sTemplate);
		
		foreach ($aObjects as $object) {
			$response->addObject ($object);
		}
		
		$response->addObject (new Array2XML ('pages', array (
			'onpage' => $aPages['onpage'],
			'total' => $sel->getTotalCount (),
			'page' => ++$aPages['page']
		)));
		
		if ($responseAttributes !== null) {
			foreach ($responseAttributes as $attrName => $value) {
				$response->setAttribute ($attrName, $value);
			}
		}
		
		return $response;
	}
	
	private function logPhotos (array $aPhotos, $albumId) {
		if (Regedit::getInstance()->get ('//settings/site/use_logs') == 1) {		
			$oTypeLog = TypesController::getInstance()->getTypeByName ('log_photo');
			
			// Собираем строку, в которой будут храниться адреса и ИД фотографий
			$aSPhotos = array ();
			
			foreach ($aPhotos as $oPhoto) {
				if ($oPhoto->getTypeName () != 'photo') {
					return;
				}
				$aSPhotos[] = $oPhoto->getValue('photo') . '=' . $oPhoto->getId();
			}
			
			$aSPhotos = array_reverse ($aSPhotos);
			$sPhotos = implode (',', $aSPhotos);
			
			// Дальше смотрим, не добавлял ли пользователь фотографии сегодня в нужный альбом
			
			$sel = new Selection;
			$sel->addType ($oTypeLog);
			$sel->addFilter ('user_id', ExplaySession::getUserId ());
			$sel->addFilter ('album_id', $albumId);
			
			$dayStart = time () - (date ('H')*3600 + date ('i')*60 + date ('s'));
			
			$sel->addFilter ('date', $dayStart, '>=');
			$sel->addLimit (1);
			
			$res = $sel->getList ();
			
			if (count ($res)) { // Пользователь уже добавлял сегодня фотографии
				$oLog = ObjectsController::getInstance()->getObject ($oTypeLog, $res[0][0]);
				$sPhotos = $sPhotos . ',' . $oLog->getValue ('photos');
				$oLog->setValue ('photos', $sPhotos);
				$oLog->setValue ('date', time ());
				$oLog->save ();
			} else { // Не добавлял
				$oLog = new Object ($oTypeLog);
				$oLog->setValues (array (
					'photos' => $sPhotos,
					'user_id' => ExplaySession::getUserId (),
					'album_id' => $albumId,
					'date' => time ()
				));
				$oLog->createNew ();
			}
		}
	}
	
}